package com.hcx.reggie.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hcx.reggie.pojo.Employee;
import com.hcx.reggie.utils.BaseContext;
import com.hcx.reggie.utils.R;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


        log.info(request.getRequestURI());
        //判断员工的登录状态
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null) {
            BaseContext.setCurrentId((Long) employee);
            return true;
        }
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            BaseContext.setCurrentId((Long) user);
            return true;
        }
        //用户未登录写回一个json
        ObjectMapper objectMapper = new ObjectMapper();
        response.getWriter().write(objectMapper.writeValueAsString(R.error("NOTLOGIN")));
        return false;

    }
}
